/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.tompai.config.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.tompai.common.model.SysPermission;
import com.tompai.common.model.SysUser;
import com.tompai.management.user.service.SysPermissionService;
import com.tompai.management.user.service.SysUserService;

/**
 *
 * @author liinux@qq.com
 * @date 2019/10/3
 */
@Service
public class LightUserDetailsService implements UserDetailsService {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysPermissionService sysPermissionService;

	/**
	 * 授权的时候是对角色授权，而认证的时候应该基于资源，而不是角色，因为资源是不变的，而用户的角色是会变的
	 */
	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		SysUser sysUser = new SysUser();
		sysUser.setAccount(userName);
		sysUser = sysUserService.select(sysUser);
		if (null == sysUser) {
			throw new UsernameNotFoundException(userName);
		}
		/**
		 * 获取到用户按关联的所有角色对应的所有权限(资源)
		 */
		List<SysPermission> sysPermissionList = sysPermissionService.getByUserId(sysUser.getId());

		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		for (SysPermission sysPermission : sysPermissionList) {
			authorities.add(new SimpleGrantedAuthority(sysPermission.getId()));
		}
		return new SecurityUser(sysUser.getId(), sysUser.getName(), sysUser.getOrgId(), sysUser.getPassword(),
				sysUser.getAccount(), authorities);
	}
}
